package org.example.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.example.vo.UploadProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.*;
import java.util.UUID;




@Component
public class uploadUtil {

    @Resource
    UploadProperties uploadProperties;




    /**
     * 实现上传图片到OSS
     */
    public String uploadadd (MultipartFile file) throws IOException, ClientException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();


        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(uploadProperties.getEndpoint(), uploadProperties.getAccessKeyId(), uploadProperties.getAccessKeySecret());
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(uploadProperties.getBucketName(), fileName, inputStream);

        //文件访问路径
       //String url = uploadProperties.getEndpoint().split("//")[0] + "//" + uploadProperties.getBucketName() + "." + uploadProperties.getEndpoint().split("//")[1] + "/" + fileName;
        String url = uploadProperties.getEndpoint().split("//")[0] + "//" + uploadProperties.getBucketName() + "." + uploadProperties.getEndpoint().split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }



}
